package com.wangyi.fightimg.utils.http;

import android.content.Context;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author wangYi
 *         访问网络工具类
 */

public class OkHttpUtil {
    private static final int TIMEOUT_CONNECTION = 10;
    private static OkHttpUtil okHttpUtil;
    private static Retrofit retrofit;
    private static Context mContext;

    public OkHttpUtil() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .readTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)//超时时间10S
                .retryOnConnectionFailure(true)//连接失败后是否重新连接
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(ServiceUrl.BASE_IP)
                .addConverterFactory(GsonConverterFactory.create())//解析数据
                .client(okHttpClient)
                .build();
    }

    /**
     * 创建访单利
     *
     * @param context
     * @return
     */
    public static OkHttpUtil getInstance(Context context) {
        mContext = context;
        if (okHttpUtil == null) {
            synchronized (OkHttpUtil.class) {
                if (okHttpUtil == null) {
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    /**
     * post访问
     *
     * @param url
     * @param parems
     * @param showDialog
     * @param netResponse
     */
    public void post(String url, Map<String, String> parems, boolean showDialog, NetResponse<ResponseBody> netResponse) {
        Call<ResponseBody> call = retrofit.create(RetrofitService.class).executePost(url, parems);
        netResponse.context = mContext;
        netResponse.fromUrl = url;
        if (showDialog) {
            netResponse.showDialog();
        }
        call.enqueue(netResponse);
    }

    /**
     * get访问
     *
     * @param url
     * @param parems
     * @param showDialog
     * @param netResponse
     */
    public void get(String url, Map<String, String> parems, boolean showDialog, NetResponse<ResponseBody> netResponse) {
        Call<ResponseBody> call = retrofit.create(RetrofitService.class).executeGet(url, parems);
        netResponse.context = mContext;
        netResponse.fromUrl = url;
        if (showDialog) {
            netResponse.showDialog();
        }
        call.enqueue(netResponse);
    }
}
